var app = getApp();
// pages/receivedcoupons/receivedcoupons.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponList: [],
    page: 1,
    pageSize: 10,
    flag: true,
    code:'',
    is_load:false,//是否加载
    is_waiting:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCoupon();
  },
  //获取优惠券列表
  getCoupon() {
    var that = this;
    app.ajax({
      url: 'User/Coupon/userCoupon',
      data: {
        page: that.data.page,
        pageSize: that.data.pageSize
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code == 1000) {
          var list = that.data.couponList;
          res.data.data.forEach(function (v, k) {
            list.push(v);
          })
          console.log(list);
          that.setData({
            couponList: list
          })
        }
        setTimeout(() => {
          that.setData({ is_load: true, is_waiting: false });
        }, 300);
      }
    })
  },
  //使用优惠券
  UseCoupon(e){
    
  },
  setCode(e){      
      var code = e.detail.value;
      this.setData({
        code:code
      })
  },
  //兑换优惠券
  exchange(){
    var that = this;

    app.ajax({
      url: 'User/Coupon/exchangeCoupon',
      data: {
        code:that.data.code       
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code == 1000) {
            app.showToast(res.data.message);    
            that.setData({
              page:1,
              couponList:[],
            })
            that.getCoupon();
        }else{
          app.showToast(res.data.message);
        }
      }
    });
  },
  /**
   * 页面上拉触底事件的处理函数 
   */
  onReachBottom: function () {
    var that = this;
    var page = that.data.page + 1;
    that.setData({
      page: page
    })
    that.getCoupon();
  },
  //扫码
  scan: function () {
    var that = this;
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];   //当前页面
    var prevPage = pages[pages.length - 3];  //上两个页面
    if (prevPage.route =='pages/gettingWater/gettingWater'){
      wx.navigateBack({
        delta:2
      })
    }else{
    var phone = wx.getStorageSync('phone');
    if (phone == '') {
      that.setData({
        popup: true
      })
      return
    } else {
        // 只允许从相机扫码
        wx.scanCode({
          onlyFromCamera: true,
          success: (res) => {
            var newsp = res.result.split("=");
            if (newsp.length == 2 && newsp[2] != '') {
              wx.navigateTo({
                url: '../gettingWater/gettingWater?equipment_sn=' + newsp[1] + '&have=' + 1,
              })
            } else {
              app.showToast('扫码失败请重试', "none", 2000, function () { });
            }
          }
        })
      }
    }
  },
})